package pt.ua.miect.sd.simuladorpesca;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CyclicBarrier;
import javax.swing.JFrame;
import javax.swing.JWindow;
import pt.ua.miect.sd.simuladorpesca.threads.FishSchoolWorker;
import pt.ua.miect.sd.simuladorpesca.threads.ISimWorker;
import pt.ua.miect.sd.simuladorpesca.threads.CompanyOperationsWorker;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import pt.ua.miect.sd.simuladorpesca.entities.Boat;
import pt.ua.miect.sd.simuladorpesca.threads.BoatWorker;

public class Simulator extends JFrame {


    private static CyclicBarrier tickBarrier;
    private static CopyOnWriteArrayList<ISimWorker> workers;
    private static Logger logger;
    /**
     * @param args
     */
    public static void main(String[] args) {
        PropertyConfigurator.configure(args[0]);

        logger = Logger.getRootLogger();
        logger.info("Entering application.");

        SimulationConfig.loadConfiguration(args[1].toString());

        workers = new CopyOnWriteArrayList<ISimWorker>();
        tickBarrier = new CyclicBarrier(SimulationConfig.NUMBER_OPERATORS * SimulationConfig.NUMBER_BOATS_PER_OPERATORS + SimulationConfig.NUMBER_OPERATORS + SimulationConfig.NUMBER_FISH_SCHOOLS);
        logger.info("Adding Operators to the simulation");
        for (int i = 0; i < SimulationConfig.NUMBER_OPERATORS; i++) {
           String companyId = "Company"+i;
           CompanyOperationsWorker ow =  new CompanyOperationsWorker(companyId,tickBarrier,SimulationConfig.NUMBER_BOATS_PER_OPERATORS);
           registerWorker(ow);
           logger.info("Adding Boats for Company "+i);
            for (Boat boat : ow.getCompany().getBoats()) {
                BoatWorker bw = new BoatWorker(tickBarrier, boat);
                registerWorker(bw);
            }
           //TODO: add log
        }
        logger.info("Adding Fish Schools to the simulation");
        for (int j = 0; j < SimulationConfig.NUMBER_FISH_SCHOOLS; j++) {
            FishSchoolWorker fw = new FishSchoolWorker("FishSchool"+j,tickBarrier);
            registerWorker(fw);
            //TODO: add log
        }
//        for (ISimWorker w : workers) {
//            w.start();
//        }
        new Simulator().show();
    }

    public static void registerWorker(ISimWorker worker) {
       if(!workers.contains(worker))
       {
           workers.add(worker);
       }

    }

    public static void unregisterWorker(ISimWorker worker) {
        workers.remove(worker);
    }


    public Simulator()
    {
        this.setSize(800, 640);

    }
}
